var recipe = new Array();

function addIngredient(){
	var count = insertNewRow("ingredients");
	$(".ingredients label.count:last").attr("for","i-"+count).text(count);
	$(".ingredients input.quantity:last").attr("name","q-"+count);
	$(".ingredients input.ingredient:last").attr("name","i-"+count);
}

function addDirection(){
	var count = insertNewRow("directions");
	$(".directions label:last").text(count).attr("for","d-"+count);
	$(".directions textarea:last").attr("name","d-"+count);
}

function insertNewRow(section){
	var clone = $("."+section+" span.row:first").clone();
	var count = $("."+section+" span.row").length;
	$(clone).children("input[type=text]").val("");
	$(clone).children("input[type=number]").val("");
	$("."+section+" input[type=button]:first").before($(clone));
	return $("."+section+" span.row").length;
}

function setTabs(){
	$("div.section:not(:first)").hide();
	$(".tabs li:first").addClass("selectedTab");
	$(".tabs li").click(function(){
		var selected = $(this).attr("name");
		// visibility
		$("div."+selected).show();
		$("div.section:not(."+selected+")").hide();
		
		style(selected);
	});
}

function style(selected){
	// styling
	$(".tabs li[name="+selected+"]").addClass("selectedTab");
	$(".tabs li:not([name="+selected+"])").removeClass("selectedTab");
	
	// focus
	if(selected=="ingredients")
		$("div."+selected).children(".row:first").children("input[type=number]:first").focus();
	else if(selected=="directions")
		$("div."+selected).children(".row:first").children("textarea:first").focus();
	else
		$("div."+selected).children("input[type=number]:first").focus();	
}

function next(curr,next){
	$("."+next).show();
	$("."+curr).hide();
	style(next);
}

function prev(curr,prev){
	$("."+prev).show();
	$("."+curr).hide();
	style(prev);
}

function optional(){
	$("input[type=checkbox]").change(function(){
		if($(this).attr("checked"))
			$(this).next("label.optional").text("required");
		else
			$(this).next("label.optional").text("optional");
	});
}

function readURL(input) {
	if (input.files && input.files[0]) {
		var reader = new FileReader();

		reader.onload = function (e) {
			$('#photo img').attr('src', e.target.result);
			resize($("#photo img"),200,200);
		}

		reader.readAsDataURL(input.files[0]);
	}
}

var tags = new Array();
function displayRecipe(result){
	recipe = result;
	// id
	$("#rid").val(result['rid']);
	
	// favorite
	if(result['favorite']=="1")
		$("#favorite").hide();
	else
		$("#unfavorite").hide();
		
	// delete button
	if(admin || result['author']==user_id)
		$("#delete_recipe").show();
	
	// name
	$("#name").html("<h2>"+result['name']+" <span id='author'>by "+result['author_nickname']+"</span></h2>");
	
	// photo
	var img = $("<img />");
	$(img).attr("src","php/photo.php?recipe_id="+$("#recipe_id").val());
	$(img).attr("id","recipe_photo");
	$("#photo").html($(img));
	resize("#recipe_photo",200,200);
	
	// tags
	$("#tags").html("");
	var span = $("<span />");
	for(i in result['tags']){
		tags[result['tags'][i]['tag_id']] = result['tags'][i]['name'];
		span = $("<span />");
		$(span).addClass("tags")
		.click(function(){ window.location.href="tag-recipe.php?tag="+tags[$(this).attr("id")]+"&tid="+$(this).attr("id"); });
		$(span).attr("id",result['tags'][i]['tag_id']).css("cursor","pointer");
		$(span).append(result['tags'][i]['name']);
		$("#tags").append($(span));
	}
	
	// serving size
	$("#serving_size").val(result['yield']);
	
	// author
	$("#author-recipes").click(function(){ window.location.href="user-recipe.php?author="+result['author']+"&email="+result['author_email']+"&nickname="+result['author_nickname'];});
	
	// times
	var total = parseInt(result['prep_time'])+(parseInt(result['inactive_time'])+parseInt(result['cook_time']));
	convertMinutes("#total",total);
	convertMinutes("#prep_time",result['prep_time']);
	convertMinutes("#cook_time",result['cook_time']);
	convertMinutes("#inactive_time",result['inactive_time']);
	
	// ingredients
	$("#ingredients").html("");
	for(i in result['ingredients']){
		var li = $("<li />");
		$(li).html("<label><span>"+decToFrac(result['ingredients'][i]['quantity'])+"</span> <span>"+result['ingredients'][i]['measurement']+"</span></label>"+" "+result['ingredients'][i]['ingredient']);
	
		if(result['ingredients'][i]['optional']==1){
			var span = $("<span />");
			$(span).addClass("optional");
			$(span).html("(optional)")
			$(li).append($(span));
		}
		$("#ingredients").append($(li));
	}
	
	// ingredients
	$("#directions").html("");
	for(i in result['directions']){
		var li = $("<li />");
		$(li).text(result['directions'][i]['details']);
		$("#directions").append($(li));
	}
	
	// rating
	rating = result['user_rating'];
	if(rating>0){
		$("#rate").val("You have tried this recipe.");
		$("#rate").attr("onclick","");
		$("#rate_it").slideDown();
		$("#rate_it div").unbind();
		setStars(rating-1,true,true);
	}
	setAvgRating(result['avg_rating']);
	var ratings_count = result['ratings_count'];
	if(ratings_count==0){
		$("#rating_details").hide();
	}
	else if(ratings_count==1)
		var msg = "<b>1</b> rating";
	else
		var msg = "<b>"+ratings_count+"</b> ratings";
	$("#ratings_count").html(msg);
	
	// comments
	$("#comments_header span").text(result['comments'].length);
	$("#comments ul").html("");
	for(i in result['comments']){
		var img = $("<img />");
		$(img).attr("src","php/gravatar.php?email="+result['comments'][i]['email'])
		.attr("width",40)
		.attr("height",40)
		.attr("title",result['comments'][i]['email']);
		var span = $("<span />");
		$(span).addClass("comment_photo");
		$(span).append($(img));
		var div = $("<div />");
		$(div).addClass("comment_details");
		$(div).html("Posted by <b class='email'>"+result['comments'][i]['email']+"</b> | "+result['comments'][i]['timestamp']);
		var li = $("<li />");
		$(li).append($(span));
		$(li).append($(div));
		$(li).append(result['comments'][i]['comment']);
		if(admin || user_id==result['comments'][i]['id']){
			div = $("<div />");
			$(div).addClass("delete");
			$(div).attr("id",result['comments'][i]['timestamp']);
			$(div).attr("title","Delete this comment.");
			var timestamp = result['comments'][i]['timestamp'];
			$(div).click(function(){ deleteComment($(this).attr("id"));});
			$(li).append($(div));
		}
		$("#comments ul").append($(li));
	}
	
	size_labels();
}

function convertMinutes(obj,total){
	if(total>=60){
		$(obj).html(Math.floor(total/60));
		$(obj).next("td").html("hr ");
		if(Math.floor(total%60)>0)
			$(obj).next("td").append(Math.floor(total%60)+" min");
	}
	else
		$(obj).html(total);	
}

function makeLabel(name,text){
	var label = $("<label />");
	$(label).attr("for",name)
	.html("<b>"+text+"</b>");
	return label;
}

function characterCount(obj){
	var maxChar = $(obj).attr("maxlength");
	$("#charcount span").text(maxChar);
	$(obj).bind( "keyup", function( event ) {
		var char = $(this).val().length;
		$("#charcount span").val();
		var left = parseInt(maxChar)-parseInt(char);
		$("#charcount span").text(left);
	})
}

function setStars(index,mover,dontSave){
	for(var i=0; i<5; i++){
		if(i<=index)
			$("#rate_it div").eq(i).addClass('on').css("background-image","url(images/star-on.png)");
		else
			$("#rate_it div").eq(i).removeClass('on').css("background-image","url(images/star-off.png)");
	}
	if(save)
		saveRating(true);
}

function setAvgRating(rating){
	rating--;
	for(var i=0; i<5; i++){
		if(i<=rating)
			$("#avg_rating div").eq(i).addClass('on').css("background-image","url(images/star-on.png)");
		else
			$("#avg_rating div").eq(i).removeClass('on').css("background-image","url(images/star-off.png)");
	}
}

var save = false;
function ratingSystem(){
	$("#rate_it div").mouseover( function() {
		if(!save)
			setStars($(this).index(),true);
	}).mouseout( function() {
		if(!save && $(this).index()==0)
			$(this).css("background-image","url(images/star-off.png)");
	});
	$("#rate_it div").click( function() {
		save = true;
		saveRating();
	});	
}

function convert(){
	//alert($("#recipe_id").attr("value"));
	//return;]
	$.ajax( {
        url: "php/conversion.php",
		type: "POST",
        data: "new_yield="+$("#serving_size").val()+"&rid="+$("#recipe_id").val(),
		cache: false,
		dataType: "json",
        success: function(data){
			for(var i=0; i<data['ingredients'].length; i++){
				$("#ingredients li:nth-child("+(i+1)+") label span:first").html(decToFrac(data['ingredients'][i]['quantity']));
				$("#ingredients li:nth-child("+(i+1)+") label span:last").html(data['ingredients'][i]['measurement']);
			}
		},
        error: function(data){ alert(data.responseText); }
    });
}

function decToFrac(dec){
	var num = Math.round(dec*100)/100;
	var decimal = (""+num).split(".");
	var whole = decimal[0];
	decimal = decimal[1];
	var result = "";
	if(whole && whole!=0)
		 result += whole+" ";
	if(decimal){
		decimal = approx(decimal);
		if(decimal==33)
			result += "1/3";
		else if(decimal==66)
			result += "2/3";
		else{
			var g = gcd(decimal,100);
			decimal = decimal/g;
			var denom = 100/g;
			result += decimal+"/"+denom;
		}
	}
	return result;
}

function approx(decimal){
	if(Math.abs(75-decimal)<=4)
		decimal = 75;
	else if(33-decimal<=2)
		decimal = 33;
	else if(decimal-33<=6)
		decimal = 33;
	else if(66-decimal<=2)
		decimal = 66;
	else if(decimal-66<=6)
		decimal = 66;
	else if(Math.abs(50-decimal)<=4)
		decimal = 50;
	else if(Math.abs(25-decimal)<=4)
		decimal = 25;	
	return decimal;
}

function gcd(a, b){
	if(b==0)
		return a;
	else
		return gcd(b, a%b);
}